import React, {useEffect} from 'react';
import {
    Box,
    Button,
    Grid,
    IconButton,
    Pagination,
    Paper,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    ThemeProvider
} from "@mui/material";
import PubSub from 'pubsub-js'
import PlayArrowOutlinedIcon from '@mui/icons-material/PlayArrowOutlined';
import {createTheme, useTheme} from "@mui/material/styles";
import {get163Search} from '../../utils/request/163request'
import {getQSearch} from '../../utils/request/qrequest'
import {getMgSearch} from '../../utils/request/migurequest'
import {getKgSearch} from '../../utils/request/kgrequest'
import {getKwSearch} from '../../utils/request/kwrequest'
import PropTypes from 'prop-types';

import FirstPageIcon from '@mui/icons-material/FirstPage';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';
import LastPageIcon from '@mui/icons-material/LastPage';
import Loading from "../Loading/Loading";

const theme = createTheme({
    palette: {
        myred: {
            main: '#ff0202',
            contrastText: 'white',
            light: '#ff0202'
        },
    },
});

function TablePaginationActions(props) {
    const theme = useTheme();
    const { count, page, rowsPerPage, onPageChange } = props;

    const handleFirstPageButtonClick = (event) => {
        onPageChange(event, 0);
    };

    const handleBackButtonClick = (event) => {
        onPageChange(event, page - 1);
    };

    const handleNextButtonClick = (event) => {
        onPageChange(event, page + 1);
    };

    const handleLastPageButtonClick = (event) => {
        onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
    };

    return (
        <Box sx={{ flexShrink: 0, ml: 2.5 }}>
            <IconButton
                onClick={handleFirstPageButtonClick}
                disabled={page === 0}
                aria-label="first page"
            >
                {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
            </IconButton>
            <IconButton
                onClick={handleBackButtonClick}
                disabled={page === 0}
                aria-label="previous page"
            >
                {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
            </IconButton>
            <IconButton
                onClick={handleNextButtonClick}
                disabled={page >= Math.ceil(count / rowsPerPage) - 1}
                aria-label="next page"
            >
                {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
            </IconButton>
            <IconButton
                onClick={handleLastPageButtonClick}
                disabled={page >= Math.ceil(count / rowsPerPage) - 1}
                aria-label="last page"
            >
                {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
            </IconButton>
        </Box>
    );
}
TablePaginationActions.propTypes = {
    count: PropTypes.number.isRequired,
    onPageChange: PropTypes.func.isRequired,
    page: PropTypes.number.isRequired,
    rowsPerPage: PropTypes.number.isRequired,
};





export default function SearchTable(props) {


    let {from} = props;

    let [page, setPage] = React.useState(1);
    let [perPage, setPerPage] = React.useState(10);
    const [pageCount, setPageCount] = React.useState(0);

    const [rows, setRows] = React.useState([]);
    const [keywords, setKeywords] = React.useState(props.keywords);
    const [loading, setLoading] = React.useState(false);
    // const emptyRows =
    //     page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;
    if(props.keywords !== keywords){
        setKeywords(props.keywords)
    }
    const handleChange = (event, value) => {
        page = value;
        setPage(value);
        setLoading(true);
        let result;
        if(from === '163'){

            result = //默认为 1 即单曲 , 取值意义 : 1: 单曲, 10: 专辑, 100: 歌手, 1000: 歌单, 1002: 用户, 1004: MV, 1006: 歌词, 1009: 电台, 1014: 视频, 1018:综合, 2000:声音(搜索声音返回字段格式会不一样)
                get163Search(keywords,(page-1)*perPage,perPage,1,(r) => {
                    setRows(r.v)
                    setLoading(false);
                    //console.log(r)
                }).catch(() => {
                    setLoading(false)
                })
        }else if(from === 'qq'){
            result = // 0：单曲，2：歌单，7：歌词，8：专辑，9：歌手，12：mv
                getQSearch(keywords,page,perPage,0,(r) => {
                    setRows(r.v)
                    setLoading(false);
                    //console.log(r)
                }).catch(() => {
                    setLoading(false)
                })
        }
        else if(from === 'migu'){
            //支持：song, playlist, mv, singer, album, lyric
            result = getMgSearch(keywords,page,perPage,'song',(r) => {
                setRows(r.v)
                setLoading(false);
                //console.log(r)
            }).catch(() => {
                setLoading(false)
            })
        }
        else if(from === 'kugou'){
            result = //酷狗只有歌曲搜索
                getKgSearch(keywords,page,perPage,(r) => {
                    setRows(r.v)
                    setLoading(false);
                    //console.log(r)
                }).catch(() => {
                    setLoading(false)
                })
        }
        else if(from === 'kuwo'){
            result = //0歌曲 1 专辑 2 歌单 3 歌手
                getKwSearch(keywords,page,perPage,0,(r) => {
                    setRows(r.v)
                    setLoading(false);
                    //console.log(r)
                }).catch(() => {
                    setLoading(false)
                })
        }
    }
    function init(){
        setPage(1);
        setPageCount(0);
        //console.log(from + "  from   " + keywords)
        let result;
        if(from === '163'){

            result = //默认为 1 即单曲 , 取值意义 : 1: 单曲, 10: 专辑, 100: 歌手, 1000: 歌单, 1002: 用户, 1004: MV, 1006: 歌词, 1009: 电台, 1014: 视频, 1018:综合, 2000:声音(搜索声音返回字段格式会不一样)
                get163Search(keywords,0,perPage,1,(r) => {
                    setRows(r.v)
                    setPageCount(r.count % perPage > 0 ? Math.floor(r.count / perPage) + 1 : r.count / perPage)
                    setLoading(false);
                    //console.log(r)
                }).catch(() => {
                    setLoading(false)
                })
        }else if(from === 'qq'){
            result = // 0：单曲，2：歌单，7：歌词，8：专辑，9：歌手，12：mv
            getQSearch(keywords,1,perPage,0,(r) => {
                setRows(r.v)
                setPageCount(r.count % perPage > 0 ? Math.floor(r.count / perPage) + 1 : r.count / perPage)
                setLoading(false);
                //console.log(r)
            }).catch(() => {
                setLoading(false)
            })
        }
        else if(from === 'migu'){
            //支持：song, playlist, mv, singer, album, lyric
            result = getMgSearch(keywords,1,perPage,'song',(r) => {
                setRows(r.v)
                setPageCount(r.count % perPage > 0 ? Math.floor(r.count / perPage) + 1 : r.count / perPage)
                setLoading(false);
                //console.log(r)
            }).catch(() => {
                setLoading(false)
            })
        }
        else if(from === 'kugou'){
            result = //酷狗只有歌曲搜索
            getKgSearch(keywords,1,perPage,(r) => {
                setRows(r.v)
                setPageCount(r.count % perPage > 0 ? Math.floor(r.count / perPage) + 1 : r.count / perPage)
                setLoading(false);
                //console.log(r)
            }).catch(() => {
                setLoading(false)
            })
        }
        else if(from === 'kuwo'){
            result = //0歌曲 1 专辑 2 歌单 3 歌手
            getKwSearch(keywords,1,perPage,0,(r) => {
                setRows(r.v)
                setPageCount(r.count % perPage > 0 ? Math.floor(r.count / perPage) + 1 : r.count / perPage)
                setLoading(false);
                //console.log(r)
            }).catch(() => {
                setLoading(false)
            })
        }

    }
    useEffect(async () => {
        if(keywords === ""){
            setLoading(false);
        }else
            setLoading(true);
        //console.log('loading')
        await init();

    },[keywords])
    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };


    function toPlay(row){
        return () => {

            //console.log("play：" + (row.id) + ":" + props.from)
            PubSub.publish("playMusic",{from:props.from,...row})
        }

    }

    function toAdd(row){
        return () => {
            //console.log("add:" + row.id + ":" + props.from)
            PubSub.publish("addNowMusic",{from:props.from,...row})
        }

    }

    return (
        <>
            <Loading open={loading}/>
            <TableContainer component={Paper}>
                <Table sx={{ minWidth: 500 }} aria-label="custom pagination table">
                    <TableHead>
                        <TableRow>
                            <TableCell width='36%'>歌曲</TableCell>
                            <TableCell width='20%'>歌手</TableCell>
                            <TableCell width='36%'>专辑</TableCell>
                            <TableCell width='8%'>时长</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        { rows.map((row) => (
                            <TableRow
                                key={row.id}
                                sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                                className='album-cell'
                            >
                                <TableCell component="th" scope="row">
                                    {row.name}
                                </TableCell>
                                <TableCell>{row.singer}</TableCell>
                                <TableCell>
                                    <span className='album'>{row.album}</span>
                                    <ThemeProvider theme={theme}>
                                        <Button className='playBtn' variant="contained" color='myred' onClick={toPlay(row)}><PlayArrowOutlinedIcon/>播放</Button>
                                        <Button  className='addBtn' variant="outlined" color='myred' onClick={toAdd(row)}>添加</Button>
                                    </ThemeProvider>


                                </TableCell>
                                <TableCell>{row.times}</TableCell>
                            </TableRow>
                        ))}

                        {/*{emptyRows > 0 && (*/}
                        {/*    <TableRow style={{ height: 53 * emptyRows }}>*/}
                        {/*        <TableCell colSpan={6} />*/}
                        {/*    </TableRow>*/}
                        {/*)}*/}
                    </TableBody>
                </Table>
            </TableContainer>
            <Grid
                container
                direction="row"
                justifyContent="center"
                alignItems="flex-center"
                item
                xs={12}
            >
                <Pagination count={pageCount} onChange={handleChange} page={page} sx={{marginTop:2}}/>
            </Grid>
        </>
    )
}